import { ref } from 'vue'
import { defineStore } from 'pinia'
import { constantRoutes } from '@/router'
import { store } from '@/store'
import system from '@/api/modules/system'

const modules = import.meta.glob('@/views/**/*.vue')

/**
 * 递归过滤有权限的异步(动态)路由
 *
 * @param routes 接口返回的异步(动态)路由
 * @returns 返回用户有权限的异步(动态)路由
 */
const filterAsyncRoutes = (routes) => {
  const asyncRoutes = []
  routes.forEach((route) => {
    const tmpRoute = { ...route } // ES6扩展运算符复制新对象
    // 判断用户(角色)是否有该路由的访问权限
    if (tmpRoute.component?.toString() == 'Layout') {
      tmpRoute.component = modules[`/src/views/layout/index.vue`]
    } else if (tmpRoute.component?.toString() == 'ParentView') {
      tmpRoute.component = modules[`/src/views/parentRoute/index.vue`]
    } else {
      const component = modules[`/src/views/${tmpRoute.component}.vue`]
      if (component) {
        tmpRoute.component = component
      } else {
        tmpRoute.component = modules[`/src/views/error-page/404.vue`]
      }
    }

    if (tmpRoute.children) {
      tmpRoute.children = filterAsyncRoutes(tmpRoute.children)
      tmpRoute.children = filterChildren(tmpRoute.children)
    }
    asyncRoutes.push(tmpRoute)
  })
  return asyncRoutes
}
// 过滤子级路由
function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView') {
        el.children.forEach((c) => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}
// setup
export const usePermissionStore = defineStore('permission', () => {
  // state
  const routes = ref([])
  const menus = ref([])
  // actions
  function setRoutes(newRoutes) {
    routes.value = constantRoutes.concat(newRoutes)
    menus.value = newRoutes
  }
  /**
   * 生成动态路由
   *
   * @param roles 用户角色集合
   * @returns
   */
  function generateRoutes() {
    return new Promise((resolve, reject) => {
      // 接口获取所有路由
      system
        .getRouters()
        .then(({ data: asyncRoutes }) => {
          // 根据角色获取有访问权限的路由
          const accessedRoutes = filterAsyncRoutes(asyncRoutes)
          setRoutes(accessedRoutes)
          resolve(treeDataToArr(accessedRoutes))
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  function treeDataToArr(data) {
    const res = []
    function dfs(tree) {
      const newTree = { ...tree }
      newTree.path.indexOf('/') === -1 && (newTree.path = '/' + newTree.path)
      newTree.meta.keepAlive = !newTree.meta.noCache
      delete newTree.children
      res.push(newTree)
      if (tree.children) {
        for (const item of tree.children) {
          dfs(item)
        }
      }
    }
    for (const item of data) {
      dfs(item)
    }
    return res
  }
  return { routes, menus, setRoutes, generateRoutes }
})

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
